package lv.usbpermission;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class UsbPermission {
    public static final String NAME = "usb-permission-issuer.apk";


    public static void init(final Context context) {
        if (!CmdUtils.isDeviceRooted()) {
            Toast.makeText(context, "设备未ROOT，无法获取USB权限", Toast.LENGTH_SHORT).show();
            return;
        }
        boolean reboot = checkApi();

        if (checkUsbFile()) {
            Toast.makeText(context, "已开启USB权限", Toast.LENGTH_SHORT).show();
            if (reboot) {
                Intent intent = new Intent(context, DialogActivity.class);
                intent.putExtra("reboot", reboot);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
            return;
        }

        Intent intent = new Intent(context, DialogActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);

    }

    private static boolean checkApi() {
        boolean reboot = false;
        if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.P) {
            String[] o = new String[]{"settings get global hidden_api_policy_pre_p_apps"};
            CmdUtils.CommandResult commandResult = CmdUtils.execCommand(o, true);
            if ("null".equals(commandResult.successMsg)) {
                o = new String[]{"settings put global hidden_api_policy_pre_p_apps  1"};
                commandResult = CmdUtils.execCommand(o, true);
                if (commandResult.result == 0) {
                    reboot = true;
                }
            }

            o = new String[]{"settings get global hidden_api_policy_p_apps"};
            commandResult = CmdUtils.execCommand(o, true);
            if ("null".equals(commandResult.successMsg)) {
                o = new String[]{"settings put global hidden_api_policy_p_apps  1"};
                commandResult = CmdUtils.execCommand(o, true);
                if (commandResult.result == 0) {
                    reboot = true;
                }
            }

        } else if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String[] o = new String[]{"settings get global hidden_api_policy"};
            CmdUtils.CommandResult commandResult = CmdUtils.execCommand(o, true);
            if ("null".equals(commandResult.successMsg)) {
                o = new String[]{"settings put global hidden_api_policy  1"};
                commandResult = CmdUtils.execCommand(o, true);
                if (commandResult.result == 0) {
                    reboot = true;
                }
            }
        }
        return reboot;
    }

    public static void reBoot() {
        CmdUtils.execCommand("reboot", true);
    }


    public static CmdUtils.CommandResult copyApk(File file) {
        String[] o = new String[]{" mount -o rw,remount /system ", " mount -o remount,rw /system ", " mv " + file.getPath() + " /system/priv-app/ ", " chmod 777 /system/priv-app/" + file.getName()};
        CmdUtils.CommandResult commandResult = CmdUtils.execCommand(o, true);
        if (!TextUtils.isEmpty(commandResult.errorMsg)) {

            String[] o2 = new String[]{" mount -o remount /system ", " cat " + file.getPath() + " > /system/priv-app/" + file.getName(), " chmod 777 /system/priv-app/" + file.getName()};
            commandResult = CmdUtils.execCommand(o2, true);
        }
        if (!TextUtils.isEmpty(commandResult.errorMsg)) {

            String[] o2 = new String[]{
                    "su",
                    "setenforce 0",
                    "mount -o remount,rw /",  // 明确指定/system分区
                    "cp " + file.getPath() + " /system/priv-app/",  // 使用copy而不是move
                    "chmod 644 /system/priv-app/" + file.getName(), // 使用正确的权限
                    "mount -o remount,ro /",  // 重新挂载为只读
                    "setenforce 1"
            };

            commandResult = CmdUtils.execCommand(o2, true);
        }
        if (!TextUtils.isEmpty(commandResult.errorMsg)) {

            String[] o2 = new String[]{"remount -R /system ",
                    " mv " + file.getPath() + " /system/priv-app/ ", " chmod 777 /system/priv-app/" + file.getName()};
            commandResult = CmdUtils.execCommand(o2, true);
        }
        return commandResult;
    }

    public static File copyAssets(Context context) {
        try {
            String path = context.getExternalCacheDir().getPath();
            InputStream inputStream = context.getAssets().open(NAME);
            File file = new File(path, NAME);
            FileOutputStream fos = new FileOutputStream(file);
            int len = -1;
            byte[] buffer = new byte[1024];
            while ((len = inputStream.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
            inputStream.close();
            fos.close();
            return file;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static boolean checkUsbFile() {
        return new File("/system/priv-app/usb-permission-issuer.apk").exists() || new File("/system/priv-app/usbPermissionIssuer/usbPermissionIssuer.apk").exists();
    }


}
